import * as Cesium from 'cesium';

/**
* 精确飞行到目标位置（解决所有偏移问题）
* @param {Cesium.Cartesian3} cartesian - 目标世界坐标
* @param {Object} [options] - 配置选项
* @param {number} [options.pitch=-30] - 俯仰角(度)
* @param {number} [options.range=100] - 观察距离(米)
* @param {number} [options.duration=1.5] - 动画时长(秒)
* @param {boolean} [options.terrainAware=true] - 是否考虑地形
*/
export async function flyToPosition(cartesian, options = {} , viewer ) {
    if (!Cesium.defined(cartesian)) return;

    const { pitch = -30, range = 100,duration = 1.5,terrainAware = true} = options;

    try {
        // 1. 获取精确坐标信息
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);

        // 2. 地形感知处理
        let surfaceHeight = 0;
        if (terrainAware) {
            try {
                const terrainSample = await Cesium.sampleTerrainMostDetailed(
                    viewer.terrainProvider,
                    [Cesium.Cartographic.clone(cartographic)]
                );
                surfaceHeight = terrainSample[0].height || 0;
            } catch (e) {
                console.warn("地形采样失败:", e);
            }
        }

        // 3. 计算安全高度（防止钻地）
        const safeHeight = surfaceHeight + Math.max(1, cartographic.height || 0);

        // 4. 创建目标点（使用原始经度纬度，确保精度）
        const targetPosition = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            safeHeight,
            viewer.scene.globe.ellipsoid
        );

        // 5. 智能飞行路径规划
        await viewer.camera.flyTo({
            destination: targetPosition,
            orientation: {
                heading: 0,
                pitch: Cesium.Math.toRadians(pitch),
                roll: 0
            },
            duration: duration,
            maximumHeight: safeHeight + range * 3,
            easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
            complete: function () {
                // 6. 最终位置校准（解决地形不平整问题）
                const surfaceNormal = viewer.scene.globe.ellipsoid.geodeticSurfaceNormal(
                    targetPosition,
                    new Cesium.Cartesian3()
                );
                const adjustedPosition = Cesium.Cartesian3.add(
                    targetPosition,
                    Cesium.Cartesian3.multiplyByScalar(
                        surfaceNormal,
                        -range,
                        new Cesium.Cartesian3()
                    ),
                    new Cesium.Cartesian3()
                );

                viewer.camera.setView({
                    destination: adjustedPosition,
                    orientation: {
                        heading: viewer.camera.heading,
                        pitch: Cesium.Math.toRadians(pitch),
                        roll: 0
                    }
                });
            }
        });

    } catch (error) {
        console.error("飞行定位异常:", error);
        // 应急处理：简单飞行到目标
        viewer.camera.flyTo({
            destination: cartesian,
            orientation: {
                heading: 0,
                pitch: Cesium.Math.toRadians(pitch),
                roll: 0
            },
            duration: duration
        });
    }
}